package com.shhic.hhplt.server.bkgrdui;

import com.shhic.hhplt.server.biz.*;
import com.shhic.hhplt.server.exceptions.TestReportXmlException;
import com.shhic.hhplt.server.model.*;
import com.shhic.hhplt.server.service.*;
import com.shhic.hhplt.server.util.EncryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 后台管理门面
 *
 * @author 张文硕
 */
@Controller
@RequestMapping("/bkgrd")
public class BackgroundUiController {

    @Autowired
    IUserService userService;
    @Autowired
    ITestReportService trService;
    @Resource
    ICodePersistService cpService;
    @Autowired
    ITestComplexQueryService tcxqService;
    @Resource
    ISerialCodeMaintaince serialCodeMaintaince;
    @Resource
    ITestReportHelper testReportHelper;
    @Resource
    IStatisticHelper statisticHelper;
    @Resource
    IWorkbayStateBuffer workbayStateBuffer;
    @Resource
    IExportReportHelper exportReportHelper;
    @Resource
    ITestReportAutoExportUtil testReportAutoExportUtil;
    @Autowired
    IDashboardService dashboardService;
    @Resource
    IDashboardInfoContainer dashboardInfoContainer;

    /**
     * 返回所有产品列表
     *
     * @return
     */
    @RequestMapping(value = "/getProductList.do", method = RequestMethod.GET)
    @ResponseBody
    public List<String> getProductList() {
        return userService.getAllProductList();
    }

    /**
     * 返回所有某一产品的测试项列表
     *
     * @return
     */
    @RequestMapping(value = "/getSuiteList.do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<String> getSuiteList(@RequestParam String productName) {
        return userService.getSuiteList(productName);
    }

    /**
     * 获得产品所有定义的绑定码
     *
     * @param productName
     * @return
     */
    @RequestMapping(value = "/getAllBindingCodeNameList.do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<String> getAllBindingCodeNameList(@RequestParam String productName) {
        return trService.getAllBindingCodeNameList(productName);
    }

    /**
     * 返回测试人员列表
     *
     * @return
     */
    @RequestMapping(value = "/getAllTestorList.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<String> getAllTestorList() {
        return userService.getAllTestorNameList();
    }

    /**
     * 返回产品检测报告HTML
     * <p>
     * 返回值有中文的时候，强制指定produces = "text/xml;charset=UTF-8"，其他拦截器神马的，都TMD不好使！！！！
     *
     * @param
     * @param idCode
     * @return
     */
    @RequestMapping(value = "/getProductTestReport.do", method = RequestMethod.POST, produces = "text/xml;charset=UTF-8")
    @ResponseBody
    public String getProductTestReport(@RequestParam String productName, @RequestParam String idCode) {
        ProductTestResult productTestResult = trService.getProductTestResult(productName, idCode);
        if (productTestResult == null) {
            return null;
        }
        try {
            return testReportHelper.generateHtmlStrFromTestReport(
                    testReportHelper.generateTestReportFromXml(
                            trService.getTestReportXml(
                                    productTestResult.getReportLoc())));
        } catch (TestReportXmlException e) {
            e.printStackTrace();
        }
        return null;
    }

    //查询测试结果集
    @RequestMapping(value = "/queryProductSuite.do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<ProductSuiteUi> queryProductSuite(ProductSuiteQuery query) {
        List<ProductSuite> queryProductSuite = trService.queryProductSuite(query);
        List<ProductSuiteUi> uiList = new LinkedList<ProductSuiteUi>();
        for (ProductSuite p : queryProductSuite) {
            uiList.add(ProductSuiteUi.fromProductSuite(p));
        }
        return uiList;
    }

    /**
     * 查询绑定码
     *
     * @param query
     * @return
     */
    @RequestMapping(value = "/queryProductBindingCode.do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<ProductBindingCode> queryProductBindingCode(ProductBindingCodeQuery query) {
        return trService.queryBindingCode(query);
    }

    /**
     * 查询绑定码集合
     * 按某一绑定码的范围，查询其他某些绑定码的对应表
     *
     * @param query
     * @return
     */
    @RequestMapping(value = "/queryBindingCodeCollection.do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<BindingCodeQueryResult> queryBindingCodeCollection(BindingCodeQuery query) {
        return tcxqService.queryBindingCodeCollection(query);
    }

    /**
     * 丢失某个实体的全部属性
     */
    @RequestMapping(value = "/unbinding.do", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public int lostCpc(String productName, String idCode) {
        try {
            ProductBindingCode bindingCode = new ProductBindingCode();
            bindingCode.setIdCode(idCode);
            bindingCode.setProductName(productName);
            trService.lostGroupBindingCode(bindingCode);
        } catch (Exception e) {
            return 1;
        }
        return 0;
    }


    /**
     * 导出绑定码集合
     *
     * @param query
     * @return 返回生成的文件名
     */
    @RequestMapping(value = "/exportBindingCodeCollection.do", method = RequestMethod.POST, produces = "text/xml;charset=UTF-8")
    @ResponseBody
    public String exportBindingCodeCollection(BindingCodeQuery query) {
        List<BindingCodeQueryResult> queryResult = queryBindingCodeCollection(query);
        return exportReportHelper.exportBindingCodeToExcelFile(queryResult, query);
    }

    @RequestMapping("/downloadFile.do")
    public String download(String fileName, HttpServletRequest request,
                           HttpServletResponse response,
                           @Value("${report.location}") String reportLocation) {
        File dir=new File(reportLocation);
        if(!dir.exists()){
            dir.mkdir();
        }
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            File f = new File(reportLocation + fileName);
            response.setContentType("application/x-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setHeader("Content-Length", String.valueOf(f.length()));
            in = new BufferedInputStream(new FileInputStream(f));
            out = new BufferedOutputStream(response.getOutputStream());
            byte[] data = new byte[1024];
            int len = 0;
            while (-1 != (len = in.read(data, 0, data.length))) {
                out.write(data, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 导出绑定码集合
     *
     * @param query
     * @return 返回生成的文件名
     */
    @RequestMapping(value = "/exportBindingCodeCollectionOfMany.do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<String> exportBindingCodeCollectionOfMany(BindingCodeQuery query) {
//        List<BindingCodeQueryResult> queryResult = testComplexQueryDao.queryBindingCodeCollectionByJava(query);
        List<BindingCodeQueryResult> queryResult=queryBindingCodeCollection(query);
        return exportReportHelper.exportBindingCodeToExcelFileOfMany(queryResult, query);
    }

    @RequestMapping("/downloadFileOfMany.do")
    @SuppressWarnings("all")
    public String downloadOfMany(List<String> fileNameList, HttpServletRequest request,
                                 HttpServletResponse response) {
        String rootpath = request.getSession().getServletContext().getRealPath("/");
        BufferedInputStream in = null;
        BufferedOutputStream out = null;

        for (String fileName : fileNameList) {
            try {
                File f = new File(rootpath + "exportReport/" + fileName);
                response.setContentType("application/x-excel");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                response.setHeader("Content-Length", String.valueOf(f.length()));
                in = new BufferedInputStream(new FileInputStream(f));
                out = new BufferedOutputStream(response.getOutputStream());
                byte[] data = new byte[1024];
                int len = 0;
                while (-1 != (len = in.read(data, 0, data.length))) {
                    out.write(data, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }


    /**
     * 获取全部参数
     *
     * @return
     */
    @RequestMapping(value = "/getAllParam.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<Param> getAllParam() {
        return cpService.getAllParam();
    }

    /**
     * 保存参数
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/saveParam.do", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String saveParam(Param param) {
        String rtnMsg;
        if (cpService.getParam(param.getKey()) != null) {
            cpService.deleteParam(param.getKey());
            rtnMsg = "参数更新成功";
        } else {
            rtnMsg = "参数保存成功";
        }
        cpService.insertParam(param);
        return rtnMsg;
    }

    /**
     * 删除参数
     *
     * @return
     */
    @RequestMapping(value = "/deleteParam.do", method = RequestMethod.GET, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String deleteParam(@RequestParam String key) {
        cpService.deleteParam(key);
        return "参数删除成功";
    }

    /**
     * 保存或更新序列
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateSerialCode.do", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String saveOrUpdateSerialCode(SerialCode sc) {
        cpService.insertOrUpdateSerialCode(sc);
        serialCodeMaintaince.updateSerialCode(sc);
        return "序列编码保存成功";
    }

    /**
     * 删除序列
     *
     * @return
     */
    @RequestMapping(value = "/deleteSerialCode.do", method = RequestMethod.GET, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String deleteSerialCode(@RequestParam String codeName) {
        cpService.deleteSerialCode(codeName);
        serialCodeMaintaince.notifyDeletion(codeName);
        return "序列删除成功";
    }

    /**
     * 获取全部序列编码
     *
     * @return
     */
    @RequestMapping(value = "/getAllSerialCode.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<SerialCode> getAllSerialCode() {
        return cpService.getAllSerialCode();
    }


    /**
     * 保存用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/saveUser.do", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String saveUser(User user) {
        user.setPassword(EncryUtil.encry("000000"));
        userService.insertUser(user);
        return "保存用户成功";
    }

    /**
     * 获取全部用户
     *
     * @return
     */
    @RequestMapping(value = "/getAllUser.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<User> getAllUser() {
        return userService.getAllUser();
    }

    /**
     * 删除用户
     *
     * @return
     */
    @RequestMapping(value = "/deleteUser.do", method = RequestMethod.GET, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String deleteUser(@RequestParam String username) {
        userService.deleteUser(username);
        return "用户删除成功";
    }

    /**
     * 保存工位信息
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/saveWorkbay.do", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String saveWorkbay(Workbay workbay) {
        userService.insertWorkbay(workbay);
        return "保存工位信息成功";
    }

    /**
     * 获取全部工位信息
     *
     * @return
     */
    @RequestMapping(value = "/getAllWorkbay.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<Workbay> getAllWorkbay() {
        return userService.getAllWorkbay();
    }

    /**
     * 删除工位
     *
     * @return
     */
    @RequestMapping(value = "/deleteWorkbay.do", method = RequestMethod.GET, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String deleteWorkbay(@RequestParam String workbayId) {
        userService.deleteWorkbay(workbayId);
        return "工位信息删除成功";
    }

    /**
     * 获得全部工位的实时状态
     *
     * @return
     */
    @RequestMapping(value = "/getAllRealtimeWorkayState.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<WorkbayState> getAllRealtimeWorkayState() {
        return workbayStateBuffer.getAllRealtimeWorkayState();
    }

    @RequestMapping(value = "/queryHistoryWorkbayState.do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<WorkbayState> queryHistoryWorkbayState(WorkbayStateQuery query) {
        return userService.queryHistoryWorkbayState(query);
    }

    /**
     * 查询工位统计数据
     *
     * @param query
     * @return
     */
    @RequestMapping(value = "/queryWorkbayStatistic.do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<WorkbayStatisticResult> queryWorkbayStatistic(WorkbayStatisticQuery query) {
        List<WorkbayStatisticResultDb> queryWorkbayStatistic = tcxqService.queryWorkbayStatistic(query);
        return statisticHelper.toWorkbayStatisticResultList(queryWorkbayStatistic);
    }

    /**
     * 获得自动导出报告的配置信息
     *
     * @return
     */
    @RequestMapping(value = "/getTestReportAutoExportConfig.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TestReportAutoExportConfig getTestReportAutoExportConfig() {
        return testReportAutoExportUtil.loadConfig();
    }

    /**
     * 保存自动导出报告的配置信息
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/saveTestReportAutoExportConfig.do", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String saveTestReportAutoExportConfig(TestReportAutoExportConfig cfg) {
        if (!new File(cfg.getSavePath()).isDirectory()) {
            return "保存位置不存在，请修改";
        }
        testReportAutoExportUtil.saveConfig(cfg);
        return "保存配置成功";
    }

    /**
     * 获得自动导出报告的配置信息
     *
     * @return
     */
    @RequestMapping(value = "/startExportImmediately.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String startExportImmediately() {
        testReportAutoExportUtil.startExportImmediately();
        return "开始导出测试报告";
    }

    /**
     * 获得测试报告导出结果
     *
     * @return
     */
    @RequestMapping(value = "/getTestReportExportResultList.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<TestReportExportResult> getTestReportExportResultList() {
        return testReportAutoExportUtil.getTestReportExportResultList();
    }

    /**
     * 指定上传文件夹
     *
     * @return
     */
    @RequestMapping(value = "/uploadExportedDir.do", method = RequestMethod.GET, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String uploadExportedDir(@RequestParam String dir) {
        //这里在URL中使用了中文，要记得tomcat的server中设置URIEncoding=utf-8
        testReportAutoExportUtil.uploadToFtp(dir);
        return "开始上传" + dir;
    }

    /**
     * 删除上传的文件夹
     *
     * @return
     */
    @RequestMapping(value = "/deleteExportedDir.do", method = RequestMethod.GET, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String deleteExportedDir(@RequestParam String forderName) {
        return testReportAutoExportUtil.deleteDir(forderName) ? forderName + "已删除" : "删除失败";
    }


    /**
     * 获得全部公示板对象
     */
    @RequestMapping(value = "/getAllDashboard.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<Dashboard> getAllDashboard() {
        return dashboardService.getAllDashboard();
    }

    /**
     * 保存新的电子公示板
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/newDashboard.do", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String newDashboard(Dashboard dashboard) {
        dashboardService.saveDashboard(dashboard);
        return "保存新的电子公示板成功";
    }

    /**
     * 删除公示板对象
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteDashboard.do", method = RequestMethod.GET, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String deleteDashboard(@RequestParam String dashboardName) {
        dashboardService.deleteDashboard(dashboardName);
        return "电子公示板删除成功";
    }

    /**
     * 发布信息
     *
     * @param dashboardInfo 信息
     * @return
     */
    @RequestMapping(value = "/issueInfoToDashboard.do", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String issueInfoToDashboard(DashboardInfo dashboardInfo) {
        dashboardInfo.setUpdateTimeToNow();
        dashboardInfoContainer.issueInfo(dashboardInfo);
        return "信息发布成功";
    }

    /**
     * 获得所有电子公示板视图模板文件列表
     *
     * @return
     */
    @RequestMapping(value = "/getAllDashboardViewTemplateFileName.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<String> getAllDashboardViewTemplateFileName(HttpServletRequest request) {
        String rootpath = request.getSession().getServletContext().getRealPath("/");
        File[] listFiles = new File(rootpath + "dashboard/template").listFiles(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().endsWith(".jsp");
            }
        });
        if (listFiles != null) {
            List<String> fl = new ArrayList<String>(listFiles.length);
            for (File f : listFiles) {
                fl.add(f.getName());
            }
            return fl;
        } else {
            return new ArrayList<String>(0);
        }
    }
}
